package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.user.modules.models.UserCash;
import cn.wizzer.app.user.modules.models.enums.BizTypeEnum;
import cn.wizzer.app.user.modules.models.vo.UserCashVo;
import cn.wizzer.app.user.modules.services.UserCashService;
import cn.wizzer.app.user.modules.services.account.UserAccountRecordService;
import cn.wizzer.framework.base.exceptions.BizException;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.base.service.CommonDBService;
import cn.wizzer.framework.util.Id;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.math.BigDecimal;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = UserCashService.class)
public class UserCashServiceImpl extends BaseServiceImpl<UserCash> implements UserCashService {


    public UserCashServiceImpl(Dao dao) {
        super(dao);
    }


    @Inject
    private UserAccountRecordService recordService;

    @Inject
    private CommonDBService commonDBService;

    @Override
    public Object listPage(String searchKeyword,int pageNumber, int pageSize) {
        Sql sql = Sqls.create("SELECT c.*,u.`nickName`,u.`phone` FROM user_cash c ");
        Sql countSql = Sqls.create("SELECT COUNT(1) FROM user_cash c ");

        Sql joinSql = Sqls.create("LEFT JOIN USER u ON u.id = c.user_id " +
                "where u.nickName like concat('%',@keyword,'%') " +
                "or no like concat('%',@keyword,'%') ");
        joinSql.setParam("keyword",searchKeyword);

        sql.appendSourceSql(joinSql.toString());
        sql.appendSourceSql("order by c.opAt desc");
        countSql.appendSourceSql(joinSql.toString());
        return commonDBService.listPage(UserCashVo.class, pageNumber, pageSize, sql.toString(), countSql.toString());
    }

    @Override
    public void add(BigDecimal amount, String toUser, String platformUid) {
        UserCash cash = new UserCash();
        cash.setAmount(amount);
        cash.setUserId(toUser);
        cash.setStatus(0);
        cash.setOpBy(platformUid);
        cash.setNo(Id.createOrderNo());
        this.insert(cash);
    }

    @Aop(TransAop.REPEATABLE_READ)
    @Override
    public void sure(String id, Boolean sure, String opBy) {
        UserCash record = this.fetch(id);
        if(record.getStatus()!=0){
            throw new BizException("该单已操作");
        }
        record.setOpBy(opBy);
        if (sure) {
            record.setStatus(2);
            //到账
            recordService.add(record.getUserId(), record.getAmount(), BizTypeEnum.CASH, id);
        } else {
            //失败
            record.setStatus(3);
        }
        this.update(record);
    }
}
